package com.heima.wemedia.service.impl;

import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.common.wemedia.dto.WmUserLoginDto;
import com.heima.model.common.wemedia.entity.WmUser;

import com.heima.utils.common.AppJwtUtil;
import com.heima.wemedia.dao.WmUserDao;
import com.heima.wemedia.service.WmUserService;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 自媒体用户表(WmUser)表服务实现类
 *
 * @author makejava
 * @since 2022-04-09 15:19:53
 */
@Service("wmUserService")
public class WmUserServiceImpl implements WmUserService {
    @Resource
    private WmUserDao wmUserDao;





    @Override
    public ResponseResult login(WmUserLoginDto dto) {
        //1. 校验参数
        if (StringUtils.isBlank(dto.getUsername()) || StringUtils.isBlank(dto.getPassword())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        //2. 根据用户输入的用户名查询数据库用户信息  WmUser
        WmUser wmUser = wmUserDao.queryByUsername(dto.getUsername());
        if (wmUser == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE, "用户名错误");
        }

        //3. 使用数据库保存的盐 + 用户输入的密码 加密得到密文 , 使用密文和数据库中的密文进行比对
        String pwd = DigestUtils.md5Hex(dto.getPassword() + wmUser.getSalt());
        if (!StringUtils.equals(pwd, wmUser.getPassword())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }
        //4. 使用JWT生成TOKEN,将Id塞入token中 ,返回数据
        String token = AppJwtUtil.getToken(Long.valueOf(wmUser.getId()));

        Map<String, Object> result = new HashMap<>();

        wmUser.setSalt("");
        wmUser.setPassword("");

        result.put("user", wmUser);
        result.put("token", token);

        return ResponseResult.okResult(result);
    }

    public static void main(String[] args) {
        String password = "123456";
        String salt = "abcd";

        String pwd = DigestUtils.md5Hex(password + salt);
        System.out.println(pwd);

    }
}
